package game;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.vector.Vector3f;

public class FPSController {
	private World world;
	private Vector3f vel, rot;
	private Player player;

	public FPSController(World world, Player player) {
		this.world = world;
		this.player = player;
		vel = new Vector3f(0.0f, 0.0f, 0.0f);
		rot = new Vector3f(0.0f, 0.0f, 0.0f);
	}

	public void update(int delta) {
		vel = new Vector3f(0.0f, 0.0f, 0.0f);
		if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
			vel.x -= player.speed * Math.sin(Math.toRadians(rot.x)) * delta;
			vel.z += player.speed * Math.cos(Math.toRadians(rot.x)) * delta;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
			vel.x += player.speed * Math.sin(Math.toRadians(rot.x)) * delta;
			vel.z -= player.speed * Math.cos(Math.toRadians(rot.x)) * delta;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
			vel.x -= player.speed * Math.sin(Math.toRadians(rot.x - 90)) * delta;
			vel.z += player.speed * Math.cos(Math.toRadians(rot.x - 90)) * delta;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
			vel.x -= player.speed * Math.sin(Math.toRadians(rot.x + 90)) * delta;
			vel.z += player.speed * Math.cos(Math.toRadians(rot.x + 90)) * delta;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
			vel.y += player.speed * delta;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
			vel.y -= player.speed * delta;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_Q)) {
			rot.z -= player.sensitivity;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_Q)) {
			rot.z += player.sensitivity;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_F5)) {
			world.clear();
			world.build();
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_F7)) {
			world.game.wireframe = false;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_F8)) {
			world.game.wireframe = true;
		}

		if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
			Mouse.setGrabbed(false);
		}

		if (Mouse.isButtonDown(0)) {
			Mouse.setGrabbed(true);
		}

		if (Mouse.isGrabbed()) {
			rot.x += Mouse.getDX() * player.sensitivity;
			rot.y -= Mouse.getDY() * player.sensitivity;
		}

		if (rot.y < -90) {
			rot.y = -90;
		}
		if (rot.y > 90) {
			rot.y = 90;
		}

		player.move(vel);
		player.setRot(rot);
	}
}
